package com.weiyi.mashangzhu.Roomer.Activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Adapter.CityReminderAdapter;
import com.weiyi.mashangzhu.Roomer.Adapter.SortAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.CityBean;
import com.weiyi.mashangzhu.Roomer.Bean.SortModel;
import com.weiyi.mashangzhu.Utils.CharacterParser;
import com.weiyi.mashangzhu.Utils.PinyinComparator;
import com.weiyi.mashangzhu.Weight.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CitySelectActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.city_reminder)
    ListView cityReminder;
    @BindView(R.id.layout_city_reminder)
    RelativeLayout layoutCityReminder;
    @BindView(R.id.back)
    ImageView back;
    private ListView sortListView;
    private SideBar sideBar;
    Intent intent = new Intent();
    /**
     * 显示字母的TextView
     */
    private TextView dialog;
    private SortAdapter adapter;
    private EditText mClearEditText;
    private View vHead;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;
    private List<CityBean> CityDateList = new ArrayList<>();

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    TextView addressOntime, l1c1, l1c2, l1c3, l1c4, l2c1, l2c2, l2c3, l2c4, l3c1, l3c2, l3c3, l3c4, l4c1, l4c2, l4c3, l4c4;
    public LocationClient mLocationClient = null;

    public BDAbstractLocationListener myListener = new MyLocationListener();
    String city = "";
    String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_select);
        ButterKnife.bind(this);
        back.setOnClickListener(this);
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数

        initLocation();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermission(permissions, 0x001);
        } else {
            mLocationClient.start();

        }

        initViews();
    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case 0x001:
                mLocationClient.start();
                break;
        }
    }

    private void initLocation() {

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

//        option.setIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

//        option.setWifiValidTime(5*60*1000);
        //可选，7.2版本新增能力，如果您设置了这个接口，首次启动定位时，会先判断当前WiFi是否超出有效期，超出有效期的话，会先重新扫描WiFi，然后再定位

        mLocationClient.setLocOption(option);
    }

    private void initViews() {
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        vHead = View.inflate(this, R.layout.item_hotcity, null);
//      头布局放入listView中

        addressOntime = (TextView) vHead.findViewById(R.id.address_ontime);
        addressOntime.setOnClickListener(this);
        l1c1 = (TextView) vHead.findViewById(R.id.l1c1);
        l1c1.setOnClickListener(this);
        l1c2 = (TextView) vHead.findViewById(R.id.l1c2);
        l1c2.setOnClickListener(this);
        l1c3 = (TextView) vHead.findViewById(R.id.l1c3);
        l1c3.setOnClickListener(this);
        l1c4 = (TextView) vHead.findViewById(R.id.l1c4);
        l1c4.setOnClickListener(this);
        l2c1 = (TextView) vHead.findViewById(R.id.l2c1);
        l2c1.setOnClickListener(this);
        l2c2 = (TextView) vHead.findViewById(R.id.l2c2);
        l2c2.setOnClickListener(this);
        l2c3 = (TextView) vHead.findViewById(R.id.l2c3);
        l2c3.setOnClickListener(this);

        l2c4 = (TextView) vHead.findViewById(R.id.l2c4);
        l2c4.setOnClickListener(this);
        l3c1 = (TextView) vHead.findViewById(R.id.l3c1);
        l3c1.setOnClickListener(this);
        l3c2 = (TextView) vHead.findViewById(R.id.l3c2);
        l3c2.setOnClickListener(this);
        l3c3 = (TextView) vHead.findViewById(R.id.l3c3);
        l3c3.setOnClickListener(this);
        l3c4 = (TextView) vHead.findViewById(R.id.l3c4);
        l3c4.setOnClickListener(this);
        l4c1 = (TextView) vHead.findViewById(R.id.l4c1);
        l4c1.setOnClickListener(this);
        l4c2 = (TextView) vHead.findViewById(R.id.l4c2);
        l4c2.setOnClickListener(this);
        l4c3 = (TextView) vHead.findViewById(R.id.l4c3);
        l4c3.setOnClickListener(this);
        l4c4 = (TextView) vHead.findViewById(R.id.l4c4);
        l4c4.setOnClickListener(this);


        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.addHeaderView(vHead);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                if (position!=0){
                    intent.putExtra("city", ((SortModel) adapter.getItem(position - 1)).getName()+"");
                    setResult(1, intent);
                    finish();
                }

            }
        });


        CityDateList = new Gson().fromJson(getResources().getString(R.string.cityInfo).toString(), new TypeToken<List<CityBean>>() {
        }.getType());
        SourceDateList = filledData(CityDateList);


        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);


        mClearEditText = (EditText) findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData(List<CityBean> date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < date.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date.get(i).getName() + "");

            //汉字转换成拼音
            String pinyin = date.get(i).getPinyin();
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        final List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
//            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.toUpperCase().indexOf(
                        filterStr.toString().toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        if (filterDateList.size() == 0) {
            layoutCityReminder.setVisibility(View.GONE);
        } else {
            layoutCityReminder.setVisibility(View.VISIBLE);
            cityReminder.setAdapter(new CityReminderAdapter(CitySelectActivity.this, filterDateList));
            cityReminder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent3 = new Intent();
                    intent3.putExtra("city", filterDateList.get(position).getName() + "");
                    setResult(1, intent3);
                    finish();
                }
            });
        }

//        adapter.updateListView(filterDateList);
    }

    @Override
    public void onClick(View v) {
        Intent intent2 = new Intent();
        switch (v.getId()) {
            case R.id.address_ontime:
                intent2.putExtra("city", addressOntime.getText());
                break;
            case R.id.l1c1:
                intent2.putExtra("city", l1c1.getText() + "");
                break;
            case R.id.l1c2:
                intent2.putExtra("city", l1c2.getText() + "");
                break;
            case R.id.l1c3:
                intent2.putExtra("city", l1c3.getText() + "");
                break;
            case R.id.l1c4:
                intent2.putExtra("city", l1c4.getText() + "");
                break;
            case R.id.l2c1:
                intent2.putExtra("city", l2c1.getText() + "");
                break;
            case R.id.l2c2:
                intent2.putExtra("city", l2c2.getText() + "");
                break;
            case R.id.l2c3:
                intent2.putExtra("city", l2c3.getText() + "");
                break;
            case R.id.l2c4:
                intent2.putExtra("city", l2c4.getText() + "");
                break;

            case R.id.l3c1:
                intent2.putExtra("city", l3c1.getText() + "");
                break;
            case R.id.l3c2:
                intent2.putExtra("city", l3c2.getText() + "");
                break;
            case R.id.l3c3:
                intent2.putExtra("city", l3c3.getText() + "");
                break;
            case R.id.l3c4:
                intent2.putExtra("city", l3c4.getText() + "");
                break;
            case R.id.l4c1:
                intent2.putExtra("city", l4c1.getText() + "");
                break;
            case R.id.l4c2:
                intent2.putExtra("city", l4c2.getText() + "");
                break;
            case R.id.l4c3:
                intent2.putExtra("city", l4c3.getText() + "");
                break;
            case R.id.l4c4:
                intent2.putExtra("city", l4c4.getText() + "");
                break;
            case R.id.back:
                finish();
                break;
        }
        setResult(1, intent2);
        finish();
    }

    public class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            location.getLatitude();    //获取纬度信息
            location.getLongitude();    //获取经度信息
            city = location.getCity();
            if ((city+"")==null||(city+"").equals("null")||(city+"").equals("")){
                addressOntime.setText("定位失败");
            }else {
                addressOntime.setText(city + "");
            }

            if (location.getLocType() == BDLocation.TypeGpsLocation) {

                //当前为GPS定位结果，可获取以下信息
                location.getSpeed();    //获取当前速度，单位：公里每小时
                location.getSatelliteNumber();    //获取当前卫星数
                location.getAltitude();    //获取海拔高度信息，单位米
                location.getDirection();    //获取方向信息，单位度

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                //当前为网络定位结果，可获取以下信息
                location.getOperators();    //获取运营商信息

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                //当前为网络定位结果

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                //当前网络定位失败
                //可将定位唯一ID、IMEI、定位失败时间反馈至loc-bugs@baidu.com

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                //当前网络不通

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                //当前缺少定位依据，可能是用户没有授权，建议弹出提示框让用户开启权限
                //可进一步参考onLocDiagnosticMessage中的错误返回码

            }
        }

        /**
         * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
         * 自动回调，相同的diagnosticType只会回调一次
         *
         * @param locType           当前定位类型
         * @param diagnosticType    诊断类型（1~9）
         * @param diagnosticMessage 具体的诊断信息释义
         */
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {

            if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_GPS) {

                //建议打开GPS

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_WIFI) {

                //建议打开wifi，不必连接，这样有助于提高网络定位精度！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_LOC_PERMISSION) {

                //定位权限受限，建议提示用户授予APP定位权限！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_NET) {

                //网络异常造成定位失败，建议用户确认网络状态是否异常！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CLOSE_FLYMODE) {

                //手机飞行模式造成定位失败，建议用户关闭飞行模式后再重试定位！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_INSERT_SIMCARD_OR_OPEN_WIFI) {

                //无法获取任何定位依据，建议用户打开wifi或者插入sim卡重试！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_OPEN_PHONE_LOC_SWITCH) {

                //无法获取有效定位依据，建议用户打开手机设置里的定位开关后重试！

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_SERVER_FAIL) {

                //百度定位服务端定位失败
                //建议反馈location.getLocationID()和大体定位时间到loc-bugs@baidu.com

            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_FAIL_UNKNOWN) {

                //无法获取有效定位依据，但无法确定具体原因
                //建议检查是否有安全软件屏蔽相关定位权限
                //或调用LocationClient.restart()重新启动后重试！

            }
        }


    }
}
